<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书列表</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.min.js"></script>
</head>
<body>
    <h2>图书列表</h2>
  <button onclick="window.location='/add.html'">添加</button>
  <ul>
  </ul>

  <script id="lis" type="text/html">
    <%
    books.forEach(b => {
  %>
    <li>
      <%=b._id%>--<%=b.name%>--<%=b.author%>--<%=b.price%>
      <button onclick="window.location='/update.html?id=<%=b._id%>'">修改</button>
      <button onclick="delBook('<%=b._id%>')">删除</button>
    </li>
  <%
    })
  %>
  </script>

  <script>
        //请求获取图书列表并渲染成列表
        async function getBooks(){
            const response = await axios('http://localhost:3007/book')

            const books  =response.data.data

            const html = template('lis',{books:books})

            document.querySelector('ul').innerHTML = html
        }
        
        getBooks()
    
        //点击删除指定图书
        async function delBook(id){
            await axios({
                url:'http://localhost:3007/book',
                method: 'delete',
                params:{
                    id
                }
            })
            window.location = '/books.html'
        }
    
    
    </script>
</body>
</html>